package com.itrip.utils;

import com.alibaba.fastjson.JSONObject;
import com.itrip.beans.domain.ItripUser;
import com.itrip.beans.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;

public class ToKenUtil {

    private RedisAPI redisAPI;

    public RedisAPI getRedisAPI() {
        return redisAPI;
    }

    public void setRedisAPI(RedisAPI redisAPI) {
        this.redisAPI = redisAPI;
    }

    public TokenVo createToken(ItripUser user, String userAgent){
        StringBuffer buffer = new StringBuffer();
        if(UserAgentUtil.isPc(userAgent)){
            buffer.append("token:PC-");
        }else{
            buffer.append("token:mobile-");
        }
        buffer.append(MD5.md5(user.getUserCode()));
        buffer.append("-").append(user.getId());
        buffer.append("-").append(System.currentTimeMillis());
        buffer.append("-").append(MD5.md5(userAgent).substring(0,6));
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(buffer.toString());
        tokenVo.setGenTime(System.currentTimeMillis());
        tokenVo.setExpTime(System.currentTimeMillis()+7200000);
        if(UserAgentUtil.isPc(userAgent)){
            redisAPI.setex("token",7200,JSONObject.toJSONString(tokenVo));
        }else{
            redisAPI.set("token", JSONObject.toJSONString(tokenVo));
        }
        return tokenVo;
    }
}
